package com.grj.es.service.impl;

import com.grj.es.entity.Products;
import com.grj.es.repostory.ProductsRepository;
import com.grj.es.service.ProductsService;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.HighlightQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service
public class ProductsServiceImpl implements ProductsService {

    @Resource
    private ProductsRepository productsRepository;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public void save(Products products) {
        productsRepository.save(products);
    }

    @Override
    public List<Products> findAll() {
        Iterable<Products> all = productsRepository.findAll();
        List<Products> list = new ArrayList<>();
        all.forEach(list::add);
        return list;
    }

    @Override
    public SearchHits<Products> search(String keyword) {
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder.Field highlightContent = new HighlightBuilder.Field("description");
        highlightContent.highlighterType();
        highlightBuilder.field(highlightContent);
        highlightBuilder.preTags("<em>");
        highlightBuilder.postTags("</em>");
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
               .withQuery(QueryBuilders.matchQuery("description", keyword))
                .withHighlightBuilder(highlightBuilder)
               .build();
        nativeSearchQuery.setPageable(PageRequest.of(0, 10));
        return elasticsearchRestTemplate.search(nativeSearchQuery, Products.class);
    }
}
